package get.data;

import java.io.ByteArrayInputStream;
import java.util.Scanner;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Main extends Activity {
	
	public static SQLiteDatabase db;
    public static final String URL = "http://www.interq.ro/ncit";
    	//"http://141.85.37.106:8000";
    
    public static myList<myNode> nodes;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        if(db == null || !db.isOpen())
        	db = openOrCreateDatabase(DatabaseHandler.DB_NAME, SQLiteDatabase.CREATE_IF_NECESSARY, null);
		System.out.println(db.getPath() +" "+ DatabaseHandler.checkDataBase(db));
        nodes = new myList<myNode>();
        getXML();
        
		/*try{
			String sql = "DROP table "+DatabaseHandler.NODES; 
			Main.db.execSQL(sql);
		}catch(Exception e){}*/ 
                
        Button tstatus = (Button) findViewById(R.id.GetTStatus);
        tstatus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent newIntent = new Intent(Main.this,TemperatureStatus.class);
				startActivity(newIntent);
			}
		});
        
        Button pstatus = (Button) findViewById(R.id.GetPStatus);
        pstatus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent newIntent = new Intent(Main.this,PowerStatus.class);
				startActivity(newIntent);	
			}
		});
        
        Button map = (Button) findViewById(R.id.map);
        map.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String myPath = DatabaseHandler.DB_PATH+ DatabaseHandler.DB_NAME;
				db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
				if(DatabaseHandler.checkDataBase(Main.db) == false){
					Intent newIntent = new Intent(Main.this,drag.and.drop.SetNodesPosition.class);
					startActivity(newIntent);
				}
				else {
					String sql = "SELECT * FROM "+ DatabaseHandler.NODES;
					Cursor c = Main.db.rawQuery(sql, null);
					if(c.getCount()!=nodes.size()){
						try{
							sql = "DROP table "+DatabaseHandler.NODES; 
							db.execSQL(sql);
						}catch(Exception e){} 
						Intent newIntent = new Intent(Main.this,drag.and.drop.SetNodesPosition.class);
						startActivity(newIntent);
					}
					else{
						Intent newIntent = new Intent(Main.this,get.data.ViewMap.class);
						startActivity(newIntent);
					}
				}
			}
		});
        
        Button config = (Button) findViewById(R.id.Config);
        config.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {	
				db.close();
				Intent newIntent = new Intent(Main.this,drag.and.drop.SetNodesPosition.class);
				startActivity(newIntent);
			}
		});
        config.setKeepScreenOn(true);

    }
    
    public void onStop ()
    {
    	super.onStop();
    	db.close();
    }

	private void getXML() {
	        HttpClient client = new DefaultHttpClient();
	        HttpGet getMethod=new HttpGet(URL+"/main");
	        String responseBody="";
	        try {
	    		ResponseHandler<String> responseHandler=new BasicResponseHandler();
	    		responseBody=client.execute(getMethod, responseHandler);
	    		if(responseBody.length()<5)
	    		    Toast.makeText(this, "Connection to server failed.", 20);

	    		
	    		String TAG1 = "<res:Plugin rdf:about=\"Sensei\"";
	    		String TAG2 = "<res:Resource";
	    		String TAG3 = "</res:Plugin>";
	    		
	    		String resources = responseBody;
	    		int idx = resources.indexOf(TAG1);
	    		resources = resources.substring(idx);

	    		idx = resources.indexOf(TAG2);
	    		resources = resources.substring(idx);

	    		idx = resources.indexOf(TAG3);
	    		resources = resources.substring(0,idx);
	    		System.out.println(resources);
	    		
	    		
	        	String line,currentadd="";
	        	Scanner lineScanner = new Scanner(resources);
	            lineScanner.useDelimiter("<res:");
	            
	            while(lineScanner.hasNext()){
		            line = lineScanner.next();
		    		System.out.println(line);
		    		
		            String add = detect_ipv6(line);
		            if(add!=null){
			    		System.out.println(add);
		            	currentadd = add;
		            	nodes.add(new myNode(add));
		            	nodes.get(nodes.size()-1).SetId(NodeAdaptor.URLresponse(URL+"/"+currentadd+"/p/pan_id"));
		            	nodes.get(nodes.size()-1).SetStatus(NodeAdaptor.URLresponse(URL+"/"+currentadd+"/p/status"));
		            	System.out.println(NodeAdaptor.URLresponse(URL+"/"+currentadd+"/p/pan_id"));
		            }
		            else{
		            	if(nodes.size()>0)
				            if((idx = line.indexOf("/s/"))!=-1){
				            	if(line.substring(idx+3).indexOf("temp")!=-1)
				            		nodes.get(nodes.size()-1).SetTempURL(URL+"/"+currentadd+"/s/temp");
				            	else if(line.substring(idx+3).indexOf("light")!=-1)
				            		nodes.get(nodes.size()-1).SetLightURL(URL+"/"+currentadd+"/s/light");
				            }
		            }
	            }    	
	        }catch(Exception e){
	        	System.out.println(e); 
	        }		
	}
	
    public String detect_ipv6(String s){
    	
        String ipv6 = null;
        int idx = s.indexOf("\"/>");
        if(idx>=19){
	        ipv6 = s.substring(idx-19,idx);
	        idx=0;
	        for(int i=0;i<4;i++){
	        	for(int j=0;j<4;j++){
	            	if(!(Character.isDigit(ipv6.charAt(idx)) || (ipv6.charAt(idx) <= 'f' && ipv6.charAt(idx) >='a')))
	            		return null;
	            	idx++;	
	            }
	            idx++;	
	        }	 
        }
		return ipv6;
    }    
}